package org.microservice.common.entrypoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.microservice.common.util.R;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: 齐丹枫
 * Date: 2018/6/22
 * Time: 9:00
 * To change this template use File | Settings | File Templates.
 * Description: 自定义Token异常信息,自定义AuthExceptionEntryPoint用于tokan校验失败返回信息
 */
@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException)
            throws ServletException {


      /*  Map map = new HashMap();
        map.put("code", "401");
        map.put("message", authException.getMessage());
        map.put("path", request.getServletPath());
        map.put("timestamp", String.valueOf(new Date().getTime()));*/
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), R.error(HttpServletResponse.SC_UNAUTHORIZED,"token认证失败,请重新登陆"));
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}